package com.erlang.filter;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ZGQ
 */

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * 自定义Filter 使用Servlet3.0的注解进行配置第三步的@WebFilter就是3.0的注解
 *    1）启动类里面增加 @ServletComponentScan，进行扫描
 *    2）新建一个Filter类，implements Filter，并实现对应的接口
 *    3) @WebFilter 标记一个类为filter，被spring进行扫描
 *     urlPatterns：拦截规则，支持正则
 *    4）控制chain.doFilter的方法的调用，来实现是否通过放行不放行，web应用resp.sendRedirect("/index.html");场景：权限控制、用户登录(非前端后端分离场景)等
 */
//过滤器拦截路径
@WebFilter(urlPatterns = "/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    /**
     * 容器加载的时候调用
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("===过滤进入====过滤进去====");
    }

    /**
     * 请求被拦截的时候进行调用
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤中========过滤中========");
        HttpServletRequest hrequest = (HttpServletRequest)servletRequest;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
        if(hrequest.getRequestURI().indexOf("/index") != -1 ||
                hrequest.getRequestURI().indexOf("/asd") != -1 ||
                hrequest.getRequestURI().indexOf("/online") != -1 ||
                hrequest.getRequestURI().indexOf("/hello") != -1 ||
                hrequest.getRequestURI().indexOf("/login") != -1
        ) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            wrapper.sendRedirect("/login");
        }
    }

    /**
     * 容器被销毁的时候被调用
     */
    @Override
    public void destroy() {
        System.out.println("过滤器销毁========过滤器销毁========");
    }
}
